﻿using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using Moonlite.Platform.General;
using Moonlite.ExtensionApi.GlobalInterfaces;

namespace Moonlite.Compiling
{
    public class DefaultCompiler : ICompiler, ICloneable
    {
        public string Name { get; set; }
        public string ExePath { get; set; }
        public string DefaultCLIArgs { get; set; }
        public bool AddPathToMap { get; set; }
        public CompilerType Type { get; set; }
        public Process InnerProcess { get; set; }

        public string GetRealExePath()
        {
            return String.Format("{0}\\{1}\\{2}", Application.StartupPath, Global.CompilersFolderPath, ExePath);
        }

        public int Compile(string mapPath)
        {
            InnerProcess = new Process();
            string arguments = DefaultCLIArgs;
            string realExePath = GetRealExePath();
            if (arguments == "common.j Blizzard.j")
            {
                arguments = String.Format("\"{0}\\common.j\" \"{0}\\Blizzard.j\"", Path.GetDirectoryName(realExePath));
            }

            ProcessStartInfo info = new ProcessStartInfo(realExePath, arguments + (AddPathToMap == true ? String.Format(" \"{0}\"", mapPath) : ""));
            InnerProcess.StartInfo = info;
            InnerProcess.Start();
            InnerProcess.WaitForExit();
            return InnerProcess.ExitCode;
        }

        public object Clone()
        {
            return new DefaultCompiler(Name, ExePath, DefaultCLIArgs, AddPathToMap);
        }

        public override string ToString()
        {
            return Name;
        }

        public DefaultCompiler()
            : this("", "", "", false)
        {

        }

        public DefaultCompiler(string name, string exePath, string defaultCLIArgs, bool addPathToMap)
        {
            Name = name;
            ExePath = exePath;
            DefaultCLIArgs = defaultCLIArgs;
            AddPathToMap = addPathToMap;
        }
    }
}
